import fetch from '.'

interface ILogin {
  username: string
  password: string
}
interface IResponseUser {
  code: number
  roles?: string[]
  success?: string
  error?: string
}

// TODO：node.js 还还有掌握，目前只能前端模拟一个数据库，存储登录用户的用户名及密码
interface IUserStore {
  admin: string,
  visitor: string,
  editor: string,
  [propName: string]: string  // 支持手动添加用户: 用户名: 密码（密码是唯一的）
}
const userStore: IUserStore = {
  admin: 'admin',
  visitor: 'visitor',
  editor: 'editor',
  ling: '123456',
}

/**
 * @description 登陆接口
 * @param {ILogin} data 登陆信息
 * @return Promise
 */
const login = (data: ILogin) => {
  return new Promise((resolve, reject) => {
    const { username, password } = data
    const success = (role: string): IResponseUser => ({ code: 0, roles: [role], success: '登录成功' })
    const error = (error: string): IResponseUser => ({ code: 101, error })

    // 如果没有用户，直接返回
    if (!userStore[username]) return reject(error('用户不存在'))
    // 有用户，但是用户密码错误，则直接返回
    if (userStore[username] && userStore[username] !== password) return reject(error('用户密码错误'))
    resolve(success(username))
  })
}

/**
 * @description 模拟一个接口请求
 * @param {string} url 接口地址
 * @param {ILogin} payload 请求参数
 * @return Promise
 */
function mockApi(url: string, payload: ILogin) {
  switch (url) {
    case '/login':
      return login(payload)
    default:
      return
  }
}

export const fetchLogin = ({ username, password }: ILogin) => mockApi('/login', { username, password })


// 接口测试
interface ICnode {
  page: number,
  tab: 'good' | 'share' | 'ask' | 'job' | '',
  limit: number
}
export const fetchCnodeList = (payload: ICnode) => fetch('/api' + '/v1/topics', payload, 'GET')

interface IDemo {
  name: string
}
export const fetchDemoData = (payload: IDemo) => fetch('/demo' + '/demo', payload)
